import os

import requests

LOTTIE_FILENAME_FILTER_LIST = ['av_room_list_av_room_list_tiny_wave.json']
SVGA_FILENAME_FILTER_LIST = ['chat_im_intimacy_introduction.svga']

class Packer():

    def __init__(self, app):
        self.app = app

    def prepare_lottie_and_svga(self, json_dir, images_dir, svga_dir, dry_run=False):
        ret = requests.get('http://cp-prod-public.yizhoucp.cn/api/util/get-config')
        # ret = requests.get('http://www-sandbox-316.cp-test.yizhoucp.cn/api/util/get-config')

        config = ret.json()
        lottie_config = config.get('data').get('lottie_config')
        svga_config = config.get('data').get('svga_config')

        json_urls = {}
        image_urls = {}
        svga_urls = {}

        for cat, cat_lottie in lottie_config.items():
            for key, item_list in cat_lottie.items():
                sub_json_urls, sub_image_urls = self._get_lottie_info(cat, key, item_list)
                json_urls.update(sub_json_urls)
                image_urls.update(sub_image_urls)

        for cat, cat_svga in svga_config.items():
            for key, item_list in cat_svga.items():
                sub_svga_urls = self._get_svga_info(cat, key, item_list)
                svga_urls.update(sub_svga_urls)

        for filename, json_url in json_urls.items():
            if filename in LOTTIE_FILENAME_FILTER_LIST:
                continue
            cmd = 'curl -s "%s" -o %s' % (json_url, json_dir + '/' + filename)
            self.app.shell_run(cmd, dry_run=dry_run)

        for filename, image_url in image_urls.items():
            cmd = 'curl -s "%s" -o %s' % (image_url, images_dir + '/' + filename)
            self.app.shell_run(cmd, dry_run=dry_run)

        for filename, svga_url in svga_urls.items():
            if filename in SVGA_FILENAME_FILTER_LIST:
                continue
            cmd = 'curl -s "%s" -o %s' % (svga_url, svga_dir + '/' + filename)
            self.app.shell_run(cmd, dry_run=dry_run)

    def _get_lottie_info(self, cat, key, item_list):
        json_urls = {}
        image_urls = {}
        for item in item_list:
            json_url = item.get('json_url')
            json_filename = '%s_%s_%s' % (cat, key, os.path.basename(json_url))
            json_urls[json_filename] = json_url
            image_urls.update({os.path.basename(url): url for url in item.get('image_urls', [])})
        return json_urls, image_urls

    def _get_svga_info(self, cat, key, item_list):
        svga_urls = {}
        for item in item_list:
            svga_url = item.get('svga_url')
            svga_filename = '%s_%s_%s' % (cat, key, os.path.basename(svga_url))
            svga_urls[svga_filename] = svga_url
        return svga_urls
